#include "chatclient.h"
#include <QtCore/QDebug>
#include <QJsonDocument>
#include <QJsonObject>
//! [constructor]
ChatClient::ChatClient(const QUrl &url, bool debug, QObject *parent) :
    QObject(parent),
    m_url(url),
    m_debug(debug)
{
    if (m_debug)
        qDebug() << "WebSocket server:" << url;
    connect(&m_webSocket, &QWebSocket::connected, this, &ChatClient::onConnected);
    connect(&m_webSocket, &QWebSocket::disconnected, this, &ChatClient::closed);
    connect(&m_webSocket, static_cast<void (QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error),this, &ChatClient::onSocketError);
    m_webSocket.open(QUrl(url));
}
//! [constructor]

//! [onConnected]
void ChatClient::onConnected()
{
    if (m_debug)
        qDebug() << "WebSocket connected";
    connect(&m_webSocket, &QWebSocket::textMessageReceived,
            this, &ChatClient::onTextMessageReceived);
    QJsonObject object
    {
        {"bind_id",91},
        {"msg_type",BindRole}
    };
    QJsonDocument json(object);
    QByteArray json_str = json.toJson();
    m_webSocket.sendBinaryMessage(json_str);
}
//! [onConnected]

//! [onTextMessageReceived]
void ChatClient::onTextMessageReceived(QString message)
{
    if (m_debug)
        qDebug() << "Message received:" << message;
    emit textMessageReceived(message);
}
//! [onTextMessageReceived]

void ChatClient::onSocketError(QAbstractSocket::SocketError err){
    if(m_debug)
        qDebug()<< "Websocket error:" << err ;
}

void ChatClient::send(QString message){
    m_webSocket.sendTextMessage(message);
}

void ChatClient::send(QByteArray data){
    m_webSocket.sendBinaryMessage(data);
}
